package com.powernode;

import java.util.concurrent.TimeUnit;

/**
 * 描述：
 * 作者：动力节点·武汉
 */
public class TestThreadLocal {

    /**
     * 创建一个基于线程隔离的容器
     * A线程向容器里面放数据  只能A线程里面取到
     * B线程向容器里面放数据  只能B线程里面取到
     */
    public static final ThreadLocal<String> THREAD_LOCAL=new ThreadLocal<>();

    public static void main(String[] args) {
        new Thread(()->{
//            THREAD_LOCAL.set("张三-name");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            getName();
        },"张三").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                THREAD_LOCAL.set("李四-name");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                getName();
            }
        },"李四").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                THREAD_LOCAL.set("王五-name");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                getName();
            }
        },"王五").start();
    }


    /**
     * 模仿工具类方法
     */
    public static void getName(){
        String s = THREAD_LOCAL.get();
        System.out.println(Thread.currentThread().getName()+":"+s);
    }
}
